﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;

namespace Common
{
    public class UploadFileHandler
    {
        public void UploadFile(Guid StudyId, string fileName, Stream data)
        {
#if (DEBUG)
            UriBuilder ub = new UriBuilder(Common.ConfigurationSettings.UploadFileUrl_local);
#else
            UriBuilder ub = new UriBuilder(Common.ConfigurationSettings.UploadFileUrl);
#endif
            ub.Query = string.Format("filename={0}&studyId={1}", fileName, StudyId);
            WebClient c = new WebClient();
            c.OpenWriteCompleted += (sender, e) =>
            {
                PushData(data, e.Result);
                e.Result.Close();
                data.Close();
            };
            c.OpenWriteAsync(ub.Uri);

        }

        private void PushData(Stream input, Stream output)
        {
            byte[] buffer = new byte[4096];
            int bytesRead;

            while ((bytesRead = input.Read(buffer, 0, buffer.Length)) != 0)
            {
                output.Write(buffer, 0, bytesRead);
            }
        }
    }
}